package com.xxrl.shop.service;

import com.xxrl.shop.domain.Apply;
import com.xxrl.shop.repository.ApplyRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author mis
 */
@Service
public class ApplyService {

    private final Logger logger = LoggerFactory.getLogger(ApplyService.class);

    private final ApplyRepository applyRepository;

    private final SimpleDateFormat dateFormatter;

    public ApplyService(ApplyRepository applyRepository) {
        this.applyRepository = applyRepository;
        this.dateFormatter =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }

    public Page<Apply> findAll(PageRequest pageRequest) {
        return applyRepository.findAll(pageRequest);
    }

    public boolean exists(Long id) {
        return applyRepository.existsByUserId(id);
    }

    public void delete(Long id) {
        applyRepository.deleteByUserId(id);
    }

    public void insert(Long id) {
        Apply apply = new Apply();
        apply.setUserId(id);
        apply.setSubmitDate(dateFormatter.format(new Date()));
        logger.info("user {} send a apply to be merchant at {}", apply.getUserId(),apply.getSubmitDate());
        applyRepository.save(apply);
    }
}
